package com.xindaoapp.happypet.fragments;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.activity.PrivateLetterActivity;
import com.xindaoapp.happypet.activity.PushMessageActivity;
import com.xindaoapp.happypet.adapter.MessageCenterAdapter;
import com.xindaoapp.happypet.adapter.MessageCenterAdapter.MESSAGETYPE;
import com.xindaoapp.happypet.adapter.MessageCenterAdapter.ViewHolder;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.MessageCenterInfo;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.KeyValuePair;
import com.xindaoapp.happypet.utils.xdConfig;

/**
 * 消息中心
 * 
 * @author chenghao
 * 
 */
public class MessageFragment extends BaseFragment {
    private PullToRefreshListView mPullToRefreshListView;

    private MessageCenterAdapter mAdapter;
    private ReceiveJpush mReceiveJpush;
    private AudioButtonJpush mAudioButtonJpush;
    private View mNoData;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_message, container, false);
    }

    @Override
    protected void initEvents(View view) {
        super.initEvents(view);
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        mNoData = view.findViewById(R.id.no_data);
        mPullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listview);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        mPullToRefreshListView.setOnRefreshListener(mOnRefreshListener);
        mPullToRefreshListView.getRefreshableView().setOnItemClickListener(mOnItemClickListener);
        mPullToRefreshListView.getRefreshableView().setOnItemLongClickListener(
                mOnItemLongClickListener);
        mReceiveJpush = new ReceiveJpush();
        getActivity().registerReceiver(mReceiveJpush,
                new IntentFilter(Constants.ACTION_RECEIVED_NOTICE));
        mAudioButtonJpush = new AudioButtonJpush();
        getActivity().registerReceiver(mAudioButtonJpush,
                new IntentFilter(Constants.ACTION_AUDIO_SETTING_CHANGED));
    }

    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MessageCenterInfo info = (MessageCenterInfo) parent.getAdapter().getItem(position);
            handleOnClick(info, ((ViewHolder) view.getTag()).isNew);
        }
    };

    private void handleOnClick(MessageCenterInfo info, View isNew) {
        if (info.type.equals(MESSAGETYPE.APP_PM.type)) {
            Intent i = new Intent(getActivity(), PrivateLetterActivity.class);
            i.putExtra(Constants.KEY_TOUID, info.authorid);
            i.putExtra(Constants.KEY_USERNAME, info.author);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getActivity().startActivity(i);
        } else if (info.type.equals(MESSAGETYPE.POST.type)) {
            Intent i = new Intent(getActivity(), PostDetailActivity.class);
            i.putExtra(Constants.KEY_POST_TID, info.tid);
            i.putExtra("pageNum", info.curpage);
            i.putExtra("floor", info.curposition);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getActivity().startActivity(i);
        } else if (info.type.equals(MESSAGETYPE.SYSTEM.type)) {
            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                    SystemInformFragment.class.getCanonicalName());
            Bundle bundle = new Bundle();
            intent.putExtra(Constants.KEY_BUNDLE, bundle);
            getActivity().startActivity(intent);
        }
        if (info.isnew == 1) {
            info.isnew = 0;
            isNew.setVisibility(View.GONE);
            HappyPetApplication.get().getMoccaApi().noticeClick(info.id, new IRequest<Boolean>() {

                @Override
                public void request(Boolean t) {
                    if (t) {
                        Constants.NoticeLabel.sHasNewMessageNotice = true;
                    } else {
                        Constants.NoticeLabel.sHasNewMessageNotice = false;
                    }
                    Intent notice = new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                    getActivity().sendBroadcast(notice);
                }
            });
        }
    }

    private final OnItemLongClickListener mOnItemLongClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            delete(((MessageCenterInfo) parent.getAdapter().getItem(position)));
            return false;
        }
    };

    private void delete(final MessageCenterInfo info) {
        AlertDialog dialog =
                new AlertDialog.Builder(getActivity()).setTitle("提醒").setMessage("确认删除？")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                HappyPetApplication
                                        .get()
                                        .getMoccaApi()
                                        .deleteNoticeMessage(info.id,
                                                info.type.equals(MESSAGETYPE.SYSTEM.type),
                                                new IRequest<Boolean>() {

                                                    @Override
                                                    public void request(Boolean t) {
                                                        if (t) {
                                                            mAdapter.getResult().remove(info);
                                                            mAdapter.notifyDataSetChanged();

                                                            if (mAdapter.getResult().size() == 0) {
                                                                mNoData.setVisibility(View.VISIBLE);
                                                                Constants.NoticeLabel.sHasNewMessageNotice =
                                                                        false;
                                                                getActivity()
                                                                        .sendBroadcast(
                                                                                new Intent(
                                                                                        Constants.KEY_NOTICE_STATE_CHANGED));
                                                            }

                                                            Toast.makeText(getActivity(), "删除成功！",
                                                                    Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            Toast.makeText(getActivity(), "删除失败！",
                                                                    Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                });
                            }
                        }).setPositiveButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {}
                        }).create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private final OnRefreshListener<ListView> mOnRefreshListener =
            new OnRefreshListener<ListView>() {

                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    onLoadData();
                }
            };

    @Override
    protected void onLoadData() {
        super.onLoadData();
        getMoccaApi().getMessageCenterInfos(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                new IRequest<KeyValuePair<Integer, List<MessageCenterInfo>>>() {

                    @Override
                    public void request(KeyValuePair<Integer, List<MessageCenterInfo>> t) {
                        if (t != null && t.second != null) {
                            if (t.first != 0) {
                                Constants.NoticeLabel.sHasNewMessageNotice = true;
                                Intent notice = new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                                mActivity.sendBroadcast(notice);
                            } else {
                                Constants.NoticeLabel.sHasNewMessageNotice = false;
                                Intent notice = new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
                                mActivity.sendBroadcast(notice);
                            }
                            if (t.second.size() == 0) {
                                mNoData.setVisibility(View.VISIBLE);
                            } else {
                                mNoData.setVisibility(View.GONE);
                                mAdapter =
                                        new MessageCenterAdapter(mActivity, t.second,
                                                Constants.PAGE_SIZE, R.layout.item_message_center,
                                                R.layout.item_loading);
                                mPullToRefreshListView.setAdapter(mAdapter);
                            }
                            onDataArrived(true);
                        } else {
                            onDataArrived(false);
                        }
                        mPullToRefreshListView.onRefreshComplete();
                    }
                });
        getPushAudioSwitch(new IRequest<Boolean>() {

            @Override
            public void request(Boolean t) {
                isCheckOn = t;
                if (t) {
                    setTopBarRightButtonDrawable(R.drawable.btn_lingdang);
                } else {
                    setTopBarRightButtonDrawable(R.drawable.sound_off);
                }
            }
        });
    }

    private boolean isCheckOn;

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mReceiveJpush);
        getActivity().unregisterReceiver(mAudioButtonJpush);
    }

    @Override
    protected String getTitleName() {
        return "消息中心";
    }

    @Override
    protected int getRightDrawable() {
        return isCheckOn ? R.drawable.btn_lingdang : R.drawable.sound_off;
    }

    @Override
    protected void setRightViewListener(View view) {
        super.setRightViewListener(view);
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (UserState.isLogged()) {
                    startActivity(new Intent(getActivity(), PushMessageActivity.class));
                }
            }
        });
    }

    /**
     * 获取推送声音开关
     * 
     * @param iRequest
     */
    private void getPushAudioSwitch(final IRequest<Boolean> iRequest) {
        RequestParams params = new RequestParams();
        XDHttpClient.post(xdConfig.PUSHMESSAGE, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                try {
                    iRequest.request(new JSONObject(content).getJSONObject("info")
                            .getInt("isaudio") == 1 ? true : false);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }

    @Override
    protected boolean showBackButton() {
        return false;
    }

    class ReceiveJpush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            onLoadData();
        }

    }

    class AudioButtonJpush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra(Constants.KEY_AUDIO_SETTING, true)) {
                isCheckOn = true;
                setTopBarRightButtonDrawable(R.drawable.btn_lingdang);
            } else {
                isCheckOn = false;
                setTopBarRightButtonDrawable(R.drawable.sound_off);
            }
        }

    }
}
